<?php
/**
 * 发仔<i@fazi.me> 2018-08-07
 */
namespace app\open\model;

use app\base\exception\BaseException;
use think\model;
use think\Db;
use traits\model\SoftDelete;
class CompanyStrength extends model
{
    use SoftDelete;
    protected $autoWriteTimestamp = true;

    public function company() {
        return $this->hasOne('Company','company_id','company_id','company','left')->setEagerlyType(0);
    }
    public function car() {
        return $this->hasOne('Car','car_id','car_id','car','left')->setEagerlyType(0);
    }

    /**
     * @param $param
     * @return false|int
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function edit($param) {
        $data = $this->get($param['id']);
        //审核后不允许更改
        if( in_array($data['state'],[2,6]) ) {
            throw new BaseException('审核通过后不允许更改信息');
        }
        $rslt = $this->allowField(true)->except('car_id,state')->isUpdate()->save($param);
        return $rslt;
    }

    /**
     * @param $param
     * @return CompanyStrength
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function bindCar($param) {

        //车辆
        $car = (new Car())->get($param['car_id']);
        if(empty($car)) {
            throw new BaseException('车辆不存在');
        }
        if(!empty($car->company_strength_id)) {
            throw new BaseException('车辆已经绑定过编制');
        }
        //编制
        $data = $this->get($param['id']);
        //绑定状态
        if( in_array($data->state,[99]) ) {
            throw new BaseException('编制已经绑定过车辆');
        }
        //2首次 22更新
        if(!empty($data->state) && !in_array($data->state,[2,22])) {
            throw new BaseException('审核未通过，不能绑定车辆');
        }
        //公司必须保持一致
        if(empty($data->company_id) || empty($car->company_id) || $data->company_id != $car->company_id) {
            throw new BaseException('所有单位（公司）非法，不能进行绑定');
        }

        // 启动事务
        Db::startTrans();
        try {
            //编制表更新
            Db::name('CompanyStrength')->where('id',$param['id'])->update(['car_id'=>$param['car_id'],'state'=>99]);
            //车辆表更新
            Db::name('car')->where('car_id',$param['car_id'])->setField('company_strength_id',$param['id']);
            Db::name('CompanyStrengthHistory')->where('car_id',$param['car_id'])->setField('company_strength_id',$param['id']);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new BaseException('数据更新失败，请重试');
        }

        return true;
    }
}